You are on page 1of 292

Introduction to Java

© Copyrights aurionPro Solutions Ltd.


Java’s Lineage
C language was result of the need for
structured, efficient, high-level language
replacing assembly language
C++, that followed C, became the common
(but not the first) language to offer OOP
features, winning over procedural languages
such as C
Java, another object oriented language
offering OOP features, followed the syntax of
C++ at most places, but offered many more
features

© Copyright aurionPro Solutions Ltd.


Features of
Java
Completely Object-Oriented

Simple

Distributed : full support for TCP/IP protocol,


developing distributed applications is easy

Robust : Strongly typed language

Secure

© Copyright aurionPro Solutions Ltd.


Features of Java
Architecture Neutral : Platform independent

Interpreted and Compiled

Dynamic

Multithreaded : Concurrent running tasks

© Copyright aurionPro Solutions Ltd.


Features added in Java 1.1
Java-Beans : Component Technology
Serialization
Remote Method Invocation
JDBC
Java Native Interface
Inner classes

© Copyright aurionPro Solutions Ltd.


in Java 2 (Java
1.2)
Java Swing
CORBA : Common Object Request Broker
Architecture
Digital Certificates : ensures security policies
Collection API : e.g. linked list, dynamic array

© Copyright aurionPro Solutions Ltd.


Features added
in Java 1.3
XML Processing
JDBC 3.0 API
Swing Drag and drop
Internationalization
Performance Improvement in Reflection APIs
JNDI
Java Print service API

© Copyright aurionPro Solutions Ltd.


Features added in 1.4

New Security certificates added


New Swing Features
Regular expressions
New I/O API
Logging
Secure Sockets
Assertions

© Copyright aurionPro Solutions Ltd.


Features
added in 1.5
Ease of Development
generic types, metadata, auto boxing, an enhanced for loop, enumerated types, static
import, C style formatted input/output, variable arguments, concurrency utilities, and
simpler RMI interface generation

Scalability and Performance


Introduction of class data sharing in the Hot Spot JVM

Monitoring and Manageability


The JVM Monitoring & Management API specifies a comprehensive set of
instrumentation of JVM internals to allow a running JVM to monitored.

Desktop Client
 Miscellaneous Features
 Core XML Support
 Supplementary Character Support
 JDBC RowSets

© Copyright aurionPro Solutions Ltd.


Platform Independence
Unix on Pentium System
Macintosh PowerPC system
.java file Class Loader
Bytecode PowerPC
verifier machine level
Java JIT compiler instructions
compiler

Class file
containing Windows Pentium PC system
Bytecodes Class Loader
Bytecode Pentium
Class Loader Verifier machine level
Bytecode JIT compiler instructions
verifier
JIT compiler

© Copyright aurionPro Solutions Ltd.


Platform Independence
(Contd.)
Platform independence primarily helps Java
Applets to be executed on any platform
Allows execution of Applet class files
compiled on remote system, downloaded
over the internet
Typically, however, on Java based Web-
applications (i.e. J2EE applications), Java
classes are compiled and executed on the
same platform

© Copyright aurionPro Solutions Ltd.


Difference between JRE
and JDK
JRE is the ‘Java Runtime Environment'. It is
responsible for creating a Java Virtual
Machine to execute Java class files (i.e run
Java programs)
JDK is the ‘Java Development Kit'. It
contains tools for Development of Java
code (e.g. Java Compiler) and execution of
Java code (e.g. JRE)
JDK is a superset of JRE. It allows you to
both write and run programs

© Copyright aurionPro Solutions Ltd.


Relation between Java and
Sun
Sun Microsystems defined and published
Java Language Specification
Sun also offers freely downloadable
reference implementation of Java Language
in the form of Sun JDK and Sun JRE
Other companies can also provide
implementation of Java Specification
Few examples of companies who provide
their own JRE are: IBM, Microsoft, BEA

© Copyright aurionPro Solutions Ltd.


Technologies
(JDK, J2EE,J2ME,….)

Java SE - Java SE Development Kit (JDK)


Java EE -Java EE 5 SDK
Java ME
 Connected Device Configuration (CDC)
 Sun Java Wireless Toolkit for CLDC,

JavaFX
 JavaFX Script
 JavaFX Mobile

© Copyright aurionPro Solutions Ltd.


First Simple
Program

//this is my first program


class Example {
/* the execution starts here */
public static void main(String args[]) {
System.out.println(“Welcome to Java “);
}
}

© Copyright aurionPro Solutions Ltd.


Compile and
Run Program
To compile the program:
c:\javac Example.java

To run it:


c:\java Example

© Copyright aurionPro Solutions Ltd.


Language Fundamentals

© Copyrights aurionPro Solutions Ltd.


Variables
Basic unit of storage in a Java program
Three types of variables:
Instance variables
Static variables
Local variables
Parameters
Each variable type has different scope
Formal parameters (i.e. arguments to
function) are similar to local variables

© Copyright aurionPro Solutions Ltd.


Data types
Type Size/Format Description

byte 8-bit Byte-length integer


short 16-bit Short Integer
int 32-bit Integer
long 64-bit Long Integer
float 32-bit IEEE 754 Single precision floating point

double 64-bit IEE 754 Double precision floating point

char 16-bit A single character


boolean 1-bit True or False

© Copyright aurionPro Solutions Ltd.


Default Values
Integer : 0
Character : ‘\u0000’
Decimal : 0.0
Boolean : false
Object Reference : null

© Copyright aurionPro Solutions Ltd.


Operators
Arithmetic operators:
+, - , * , / ,%
++, --
+-, -=, *= , /= , %=
Relational operators:
 == , != , >=,>,<=,<
assignment(=), ternary(?)

© Copyright aurionPro Solutions Ltd.


Operators
Precedence
Postfix expr++ expr—
Unary ++expr --expr +expr -expr ~ !
Multiplicative */%
Additive +-
Shift << >> >>>
Relational < > <= >= instanceof
Equality == !=
bitwise &^|
logical && ||
Ternary ?:
Assignment = += -= *= /= %= &= ^= |= <<=
>>= >>>=
© Copyright aurionPro Solutions Ltd.
Control Flow
Statements
if-then
if-then-else
switch
while
do-while
for
Branching Statements
break
continue
return

© Copyright aurionPro Solutions Ltd.


Memory
Management
Dynamic and Automatic
No delete operator
Implemented by Garbage Collector
Garbage Collector is the Lowest Priority
Daemon Thread
It runs in the background when JVM starts
Collects all the unreferenced objects
Frees the space occupied by these objects
System.gc() method can be called to “hint”
the JVM that it should invoke garbage
collector, however, there is no guarantee that
it would be invoked. It is implementation
dependent
© Copyright aurionPro Solutions Ltd.
Arrays
A group of like-typed variables referred by
common name
Declaring an array
int arr [];
arr = new int[10]
int arr[] = {2,3,4,5};
int two_d[][] = new int[4][5];
Java arrays are asymmetrical arrays

© Copyright aurionPro Solutions Ltd.


Arrays
Arrays of objects too can be created
Example 1 :
 Box Barr[] = new Box[3];
 Barr[0] = new Box();

 Barr[1] = new Box();

 Barr[2] = new Box();

Example 2:
 String[] Words = new String[2];
 Words[0]=new String(“Bombay”);

 Words[1]=new String(“Pune”);

© Copyright aurionPro Solutions Ltd.


OOP Concepts

© Copyrights aurionPro Solutions Ltd.


Encapsulation
Encapsulation describes the ability of an
object to hide its data and methods from the
rest of the world - one of the fundamental
principles of OOP (Object Oriented
Programming)
Encapsulation is implemented using
different access specifiers such as private,
protected, public etc

© Copyright aurionPro Solutions Ltd.


Introduction
to Classes
The general form of a class
class < class_name>{
type var1;…..

Type method_name(arguments ){
body
}…..
} //class ends.

© Copyright aurionPro Solutions Ltd.


Introduction
to Classes
A Simple Class
class Box{
double width;
double height;
double depth;
double volume(){
return width*height*depth;
} //method volume ends.
}//class box ends.

© Copyright aurionPro Solutions Ltd.


Declaring Objects
class impl{
public static void main(String a[]){
//declare a reference to object
Box b;
//allocate a memory for box object.
b = new Box();
// call a method on that object.
b.volume(); }
} © Copyright aurionPro Solutions Ltd.
Types of class
members
default access members (No access
specifier)
private members
public members
protected members

© Copyright aurionPro Solutions Ltd.


Inheritance
One of the major pillars of OO approach
Allows creation of hierarchical classification
Advantage is reusability of the code
Once a class is defined & debugged , same
class can be used to create further derived
classes
Already written code can be extended as and
when required to adopt different situations

© Copyright aurionPro Solutions Ltd.


Inheritance (Contd.)
Inherited members can be used with the
super keyword
super() ;// calls parent class constructor
super.overriden() ;// calls an overriden
method of the base class

© Copyright aurionPro Solutions Ltd.


Inheritance
(Contd.)
Class Base {
public void meth1() {
System.out.println(“Method1 of
Base”);
}
}
Class Derived {
public void meth1() {
super.meth1();
System.out.println(“Method1 of
Derived”);
}
} © Copyright aurionPro Solutions Ltd.
Inheritance
(Contd.)
class Test
{
public static void main(String args[]){
Derived d1=new Derived();
d1.meth1();
}
}

© Copyright aurionPro Solutions Ltd.


Inheritance
(Contd.)
Output:
Method1 of Base
Method1 of Derived

© Copyright aurionPro Solutions Ltd.


Polymorphis
m
An objects ability to decide what method to
apply to itself depending on where it is in
the inheritance hierarchy
Can be applied to any method that is
inherited from a super class
Allows to design & implement systems that
are more easily extensible

© Copyright aurionPro Solutions Ltd.


Abstract class
A class that provides common behavior
across a set of subclasses, but is not itself
designed to have instances that work
One or more methods are declared but may
or may not be defined
Advantages:
Reusability of code
Help at places where implementation is not
available

© Copyright aurionPro Solutions Ltd.


Abstract
class (Contd.)
Any class that has even one method as
abstract should be declared abstract
Abstract classes can’t be instantiated
Abstract modifier cant be used for
constructors & static methods
Any sub class of an abstract class should
implement all methods or declare itself to
be abstract
An abstract class need not have only
abstract methods; can have concrete
methods too
© Copyright aurionPro Solutions Ltd.
Important Classes and
Keywords in Java

© Copyrights aurionPro Solutions Ltd.


Constants
Use the final keyword before the variable
declaration and include an initial value for
that variable
Eg:-
final float pi = 3.141592;
final boolean debug = false;
final int maxsize = 30000;

© Copyright aurionPro Solutions Ltd.


Final Classes and
Methods
Final Classes
Final classes cannot be inherited
All methods in a final class are implicitly final

Final Methods
final methods cannot be overridden
Methods declared as static are implicitly final
Also methods declared private are implicitly
final

© Copyright aurionPro Solutions Ltd.


Members
You can declare both methods and
variables to be static
Static methods has got following
restrictions
They can call only static methods
They can access static data only
Cannot refer to this or super
Static methods can access non-static
variables and non-static methods, provided
explicit instance variable is made available to
the method

© Copyright aurionPro Solutions Ltd.


Nested
classes
Class within another class
The scope of a nested class is bounded by
the scope of its enclosing class
Nested classes are of two types:
Static
Non-static
Nested classes should be used to reflect and
enforce the relationship between two classes

© Copyright aurionPro Solutions Ltd.


Anonymous
Inner classes
These classes do not have a name
Are defined at the location they are
instantiated using additional syntax with the
new operator
Typically used to create objects “on the fly”
in contexts such as return value of a
method, an argument in a method call or in
initialization of variables

© Copyright aurionPro Solutions Ltd.


Object
Superclass
Cosmic super class
Ultimate ancestor – every class in Java
implicitly extends Object
A variable of type Object can be used to refer
to objects of any type
Eg. Object obj = new Emp();
Methods in Object class are :
void finalize()
Class getClass()
String toString()

© Copyright aurionPro Solutions Ltd.


The System
Class
The System class is the class used to
interact with any of the system resources
It can not be instantiated
Contains a lot of methods and variables to
handle system I/O
Among the facilities provided by the System
class are standard input, standard output,
and error output streams

© Copyright aurionPro Solutions Ltd.


The System Class
Some of the methods in System class:
System.gc(): is a suggestion and not a
command
It is not guaranteed to cause the garbage collector to
collect
everything
System.exit(0);

© Copyright aurionPro Solutions Ltd.


Handling
String is handled as an object of class String
and not as an array of characters
String class is a better and a convenient
way to handle any operation
But one main restriction with this class is
that once an object of this class is created,
the contents cannot be changed

© Copyright aurionPro Solutions Ltd.


methods of
String class
length() : length of String
indexOf() : searches for the occurrence of a
char, or String within other String
substring() : retrieves substring from the object
trim() : to remove spaces
valueOf() : converts data to String

© Copyright aurionPro Solutions Ltd.


The String Class
String str = new String(“Pooja”);
String str1 = new String(“Sam”);
Heap Stack
Pooja
str
Sam
str1
String str = new String(“Pooja”);
String str1 = str;

Pooja str
str1
© Copyright aurionPro Solutions Ltd.
StringBuffer
Class
Peer class of String class that represents fixed
length, immutable char sequence
StringBuffer represents growable and
writeable character sequence
Insertions at particular positions are possible
through this class

© Copyright aurionPro Solutions Ltd.


Wrapper Classes
Primitives are not a part of object hierarchy
Primitives are passed by value
Object representation of primitives is required
Wrapper classes provide a way to encapsulate
simple values as objects
Integer, Double, Float, Character are all
wrapper classes

© Copyright aurionPro Solutions Ltd.


Casting of Variables
To convert one variable value to other,
wherein two variables correspond to two
different data types
Double d = 10.5;
float f = (float) b;
Widening does not require casting
Casting of References can be done, if two
classes are related to each other by
inheritance relationship
If the casting is not proper, it throws
ClassCastException
© Copyright aurionPro Solutions Ltd.
UpCasting &
DownCasting
Upcasting
Object o = new String(“HELLO”);
Serializable s = new String(“New”);

DownCasting
String s1 = (String) o;
String s2 = (Serializable) s

© Copyright aurionPro Solutions Ltd.


Parameter
Passing
Parameters or arguments passed to a
function are passed by value for primitive
data-types (e.g. int, char)
Parameters or arguments passed to a
function are passed by reference for non-
primitive data-types (e.g. All Java objects)
Java does not have concept of passing
parameters by address or pointers, similar to
what we have in C or C++ (using * to denote
a pointer to object)

© Copyright aurionPro Solutions Ltd.


Packages and Interfaces

© Copyrights aurionPro Solutions Ltd.


Interfaces – Their need
Interface defines a data-type without
implementation
The interface approach is sometimes known
as programming by contract
It’s essentially a collection of constants &
abstract methods
An interface is used via the keyword
"implements" Thus a class can be declared
as
class MyClass implements Sun, Fun{
 ... }
© Copyright aurionPro Solutions Ltd.
Interfac
es
A Java interface definition looks like a class
definition that has only abstract methods,
although the abstract keyword need not
appear in the definition

public interface Testable {


 void method1();
 void method2(int i, String s);

}

© Copyright aurionPro Solutions Ltd.


Declaring and
Using Interfaces
public interface simple_cal {
int add(int a, int b);
int i=10;
}
//Interfaces are to be implemented.
class calci implements simple_cal {
int add(int a, int b){
return a+b;
}}

© Copyright aurionPro Solutions Ltd.


Interfaces -
rules
Methods in an interface are always public &
abstract
Data members in a interface are always
public, static & final
A sub class can only have a single super
class in Java
But a class can implement any number of
interfaces
Thus flexibility is introduced in usage of
polymorphism

© Copyright aurionPro Solutions Ltd.


Interfaces &
Abstract classes
Abstract classes are used only when there is a
“is-a” type of relationship between the classes
You cannot extend more than one abstract
class
Abstract class can contain abstract as well as
implemented methods

© Copyright aurionPro Solutions Ltd.


Packages
Are a named collection of classes
Are a way of grouping related classes &
interfaces
A package can contain any number of
classes that are related in purpose, in scope
or by inheritance
Convenient for organizing your work &
separating your work from code libraries
provided by others

© Copyright aurionPro Solutions Ltd.


Packages :
Their need
Allow to organize classes into units
Reduce problems with naming conflicts
Allow to protect classes, variables &
methods in a larger way than on a class-to-
class basis

© Copyright aurionPro Solutions Ltd.


Using packages
To use a public class of a package, simple use
the full package name
E.g. Java.util.Date = new java.util.Date();
import statement: allows to import all the
public classes in a package
E.g. import java.awt.*;
If the required class is in java.lang package, it
can be used directly

© Copyright aurionPro Solutions Ltd.


Defining A Package
package com.patni.trg.demo;
// import statements here.
public class Balance {
String name;
double bal;
public Balance(String n, double b) {
name = n;
bal = b;
}

© Copyright aurionPro Solutions Ltd.


Defining A
Package
  public void show() {
if(bal<0)
System.out.print("-->> ");
System.out.println(name +
": $" + bal);
}
}

© Copyright aurionPro Solutions Ltd.


Compiling A
Package
Specify the path of the directory, where com
directory is to be created

Example
javac –d . Balance.java
javac –d E:\JavaAss\MyAss Balance.java

© Copyright aurionPro Solutions Ltd.


Package
scope access
Default: features of a class having default
scope can be accessed by all classes in the
same package

Protected: enables a feature to be accessed


by classes or interfaces of the same package
or by subclasses of the class in which it is
declared

© Copyright aurionPro Solutions Ltd.


Access Specifiers
Private No Modifier Protected Public

Same class Y Y Y Y

Same Package Subclass N Y Y Y

Same Package non-sub class N Y Y Y

Different Package Subclass N N Y Y

Diffrent Package non-subclass N N N Y

© Copyright aurionPro Solutions Ltd.


Access Specifiers

Package P1
Class A

Package P2

Class B Class C Class G Class F

© Copyright aurionPro Solutions Ltd.


Classpath
For java to be able to use a class, it has to
be able to find that class on the file system
Otherwise, the runtime flags an exception
that the class does not exist

Java uses 2 elements to find classes


 The package name
The directories listed in classpath variable

© Copyright aurionPro Solutions Ltd.


Classpath(Contd.)
classpath : points to various places where
java classes live
The specific location that Java compiler
considers as root of an package hierarchy is
controlled by classpath
e.g.
classpath = c:\jdk1.2.2\bin; c:\jdk1.4.2_03;
d:\java;

© Copyright aurionPro Solutions Ltd.


How compiler locates a
file
Compiler searches through all directories
specified in the classpath variable
If . is specified in classpath, then it also
checks current directory
If compiler still does not locate the file, it
flags a ClassNotFound Exception

© Copyright aurionPro Solutions Ltd.


Eclipse, an IDE

© Copyrights aurionPro Solutions Ltd.


What is an
IDE?
An application or set of tools that allows a
programmer to write, compile, edit, and in
some cases test and debug within an
integrated, interactive environment
IDE combines the editor, compiler, runtime
environment and debugger – all in the single
integrated application.
(e.g. When one attempts to compile code
with syntax errors, IDE shows the error
messages, and lets one jump to that line by
clicking on error message)

© Copyright aurionPro Solutions Ltd.


examples of
an IDE
Eclipse
JDeveloper
WSAD (WebSphere Studio Application
Developer)
JBuilder

© Copyright aurionPro Solutions Ltd.


Using Eclipse
as an IDE
The Eclipse Project is an open source software
development project dedicated to providing a
robust, full-featured, commercial-quality,
industry platform for the development of highly
integrated tools and rich client applications
 

© Copyright aurionPro Solutions Ltd.


Using Eclipse
as an IDE
 Our objective is to code Java programs faster
with Eclipse 3.0 as an IDE

 Eclipse3.0 features include:


 Creation and maintenance of the Java project
 Developing Packages
 Debugging a java program with variety of
tools available
 Running a Java program

© Copyright aurionPro Solutions Ltd.


Using Eclipse
as an IDE
Developing the Java program will be easier as
Eclipse editor will provide:
    Syntax highlighting
    Content/code assist
    Code formatting
    Import assistance
    Quick fix

© Copyright aurionPro Solutions Ltd.


Eclipse-
Plugins
Lomboz
Checkstyle
JDepend
PMD
Ant

© Copyright aurionPro Solutions Ltd.


Exception Handling

© Copyrights aurionPro Solutions Ltd.


Exception
Handling
Exception is an object that describes an
exceptional condition
Java Exception handling is managed by 5
keywords
try, catch
finally
throw
throws

© Copyright aurionPro Solutions Ltd.


Exception
Handling
Throwable

Exception Error

RunTime Compile Time Exception


Exception
Unchecked Exception Checked Exception

© Copyright aurionPro Solutions Ltd.


Some
Examples
Checked Exceptions include:
IOException
SQLException
ClassNotFoundException

Unchecked Exceptions include:


ArithmaticException
NullPointerException
ArrayIndexOutOfBoundsException

© Copyright aurionPro Solutions Ltd.


Using try and catch
class demo {
public static void main(String a[]) {
try {
int d = 0;
int a = 42 /d;
} catch(ArithmeticException ae) {
System.out.println(ae);
}
}}

© Copyright aurionPro Solutions Ltd.


Throw and
Throws clause
It is a way to throw an exception explicitly
Must be an object of Throwable or it’s
subclasses

Example:
public void passgrade(int a, int total) {
if (a > total)
throw new ArithmeticException();
}

© Copyright aurionPro Solutions Ltd.


Throws clause
If method is capable of throwing an exception,
then caller needs to be informed, so that they
can guard themselves against the exception
 public void passgrade(int a, int total) throws
ArithmeticException {
 if (a > total)
 throw new ArithmeticException();
 }

Throws clause is not commonly used for


Exceptions of type Error, RuntimeException, or
© Copyright aurionPro Solutions Ltd.
Finally clause
Finally clause creates a block of code that will be
executed whether or not an exception is thrown
Usage:
try {
int j = 0;
int i = d/j;
} catch (ArithmeticException ae) {
System.out.println(ae);
} finally {
System.out.println(“Always Executed”);
© Copyright aurionPro Solutions Ltd.
Application Specific
Exceptions
class ApplicationException extends Exception {
private int detail;
ApplicationException(int a)
{ detail = a;}
ApplicationException(String args) {
super(args); }
public String toString(){ return
"ApplicationException["+detail+"]";}
}

© Copyright aurionPro Solutions Ltd.


Documenting in Java
- javadoc

© Copyrights aurionPro Solutions Ltd.


What is
javadoc?
Javadoc is a tool that parses the
declarations and documentation comments
in a set of source files and produces a set of
HTML pages describing the classes, inner
classes, interfaces, constructors, methods,
and fields
To generate javadocs for the class some
commenting styles must be followed in the
program

© Copyright aurionPro Solutions Ltd.


Javadoc
Comments
A general javadoc comment
/**
* This is the typical format of a simple
documentation *comment that spans two
lines
*/
Documentation comments are recognized
only when enclosed between /** and */ and
placed immediately before class, interface,
constructor, method, or field declarations

© Copyright aurionPro Solutions Ltd.


Comments
(Contd.)
Class and interface Documentation tags
@see,@deprecated,@author,@version and
more
Example:
 /** * A class representing a window on the screen.
 * For example:

 * @author patni

 * @see java.awt.BaseWindow

 */
 class Window extends BaseWindow { ... }

© Copyright aurionPro Solutions Ltd.


Comments
(Contd.)
Field Documentation tags:
@see,@deprecated,@since,@serial and
more
Example:
 /**
 * The X-coordinate of the component.
 *
 * @see #getLocation() */ int x = 1263732;

© Copyright aurionPro Solutions Ltd.


Comments
(Contd.)
Constructor and Method Documentation Tags
@see,@param,@return,@since,@throws,@exce
ption and more
/**
 * Returns the character at the specified index. An
index
 * @param index the index of the desired character

© Copyright aurionPro Solutions Ltd.


Comments
(Contd.)
 * @return the desired character.
 * @exception StringIndexOutOfRangeException
 * if the index is not in the range
<code>0</code>
 * to <code>length()-1</code>.
 * @see java.lang.Character#charValue()
 */
 public char charAt(int index) { ... }

© Copyright aurionPro Solutions Ltd.


© Copyrights aurionPro Solutions Ltd.
Coding Conventions
Every project in aurionPro MUST follow
consistent Java Coding Conventions, unless
overridden by client for that project
Coding conventions (also known as “Coding
Guidelines”) are set of suggestive
guidelines defined for a project, that helps
to enforce consistent coding style across
developers within the project
For example, it ensures consistent and
readable names of variables, classes or
methods across application

© Copyright aurionPro Solutions Ltd.


Coding Conventions
(Contd.)
Examples of Coding Conventions Guidelines
Class level member variable should be
m_x<varname> where m indicates member
variable,
x should be replaced with i for integer, s for String etc.
 e.g. m_sUserName // String that stores User Name
Function Arguments variables (formal parameters)
should be a_x<varname> where
a indicates argument variable,
x should be replaced with i for integer, s for String etc.
 e.g.a_iProjectCode // integer argument to hold proj-
code
First letter of©every classSolutions
Copyright aurionPro shouldLtd. always be in upper
Coding Conventions
(Contd.)
How do Coding Conventions help the
project?
Helps to define the consistent ways of naming
a variable or a class or a method within
application
Improves readability of the code
Helps during defect fixing and maintenance
phase, since variable names are indicative of
its scope, type etc
Makes debugging of code person-independent
Saves efforts on documentation, since
variable/method or class names becomes self-
© Copyright aurionPro Solutions Ltd.
Coding Conventions (Contd.)

How to use Coding Conventions on the project?


Typically defined by client or senior team
member or PL before the start of the coding
phase
If not defined for a project, refer to conventions
defined by Sun
(http://java.sun.com/docs/codeconv/index.html)
Should be read and understood by every
developer before starting the code (to avoid
rework later on)
Should be adopted as part of the coding-culture
itself, and not as add-on activity applied after
functional ©coding is done
Copyright aurionPro Solutions Ltd.
Coding Conventions
(Contd.)
Coding Conventions can be found on our QMS
-> 4.4 Tables
-> GL 1 - Guidelines for Coding

Conventions defined by Sun


http://java.sun.com/docs/codeconv/index.html
that can be used for rest of the assignments
within this course

© Copyright aurionPro Solutions Ltd.


© Copyrights aurionPro Solutions Ltd.
Reviews
Being ISO-9001:2000 company, reviews
are part of the life in aurionPro
Reviews do take place for every work
product created in SDLC of a project (e.g.
Design review, test case review, code
review etc.)
Various types of reviews in Patni
Self-Review
Peer-to-peer review
Peer review

© Copyright aurionPro Solutions Ltd.


Code
Reviews
Code is reviewed by Peer (colleague)
Why Peer to Peer Reviews are required?
Everyone has a blind spot. Can’t catch one’s
own mistake
Helps to catch the defect early in the life-cycle
Defects found in reviews may be difficult or
impossible to find in testing (e.g. coding
convention defects)
It takes more efforts to find the same defect
during testing (Cost of finding defect in testing
is higher than cost of finding defect in reviews)
Enforces consistency amongst developers and
clarifies ©misunderstood points during review
Copyright aurionPro Solutions Ltd.
Review
Checklist
Code reviews should be done using a checklist,
and should cover functional reviews too
Typically code-review checklists are created
senior team member (GL) or PL or sometimes
provided by client too
If not defined for a project, refer to checklists
available on Patni KC
Should be read and understood by every
developer before starting the code creation
and code reviews
Checklist must be used by code-creator for
self-review. This will reduce the efforts during
peer-to-peer review
© Copyright aurionPro Solutions Ltd.
Checklist
(Contd.)
Typically Java Code Review checklist looks like
this
 Sample Java Code review checklist
One of the important points that code-review
checklist ensures is enforcing coding
conventions (or coding guidelines) discussed
in earlier slides
Review Findings of code-review should be
captured as code-review defects. Defects
should be fixed by code-creator, and re-
verified by the person reporting the defect

© Copyright aurionPro Solutions Ltd.


Java Property files

© Copyrights aurionPro Solutions Ltd.


Java Property
files
java.util.Properties is a platform-independent
generalization of the DOS SET environment,
or the Windows *.INI files. In Java, even each
object could have its own list of properties. A
program can determine if an entry is missing
in the property file and provide a default to
using it its place

© Copyright aurionPro Solutions Ltd.


Java
Properties
Java.util.Properties class:
The Properties class represents a persistent
set of properties. The Properties can be saved
to path from where the properties file would
be picked up. Each key and its corresponding
value in the property list is a string

© Copyright aurionPro Solutions Ltd.


Types of
properties
Property files provide a means of storing key-
value pair,which could be used by the
programs in execution

Properties can be categorized as:

User specific properties


System properties

© Copyright aurionPro Solutions Ltd.


Types of
properties
 User specific properties:
These properties are part of the
Application.properties containing a key value
pair, which can be mentioned by the program
in run

 #application.properties file contents


password=tiger

url=jdbc:oracle:thin:@192.168.12.16:1521:oracl
e8i
driver=oracle.jdbc.driver.OracleDriver
© Copyright aurionPro Solutions Ltd.
Types of
properties
System properties:
System properties give information about the
environment of the program ,in which it is
running such as JVM it is running in, Operating
System name and version, java home and
many more properties

© Copyright aurionPro Solutions Ltd.


System
Properties
System properties are read from System
class, which give information about the
environment of the Java program in which it is
running, such as:
Java.vm
Java.version
User.language
Java.home
User.region etc

© Copyright aurionPro Solutions Ltd.


Files and Streams

© Copyrights aurionPro Solutions Ltd.


Streams
Files are necessary for persisting data
Java views each file as a sequential stream of
bytes
Stream is generic term for ‘flow of data’
Different streams are used to represent
different kinds of data flow
When a file is opened, an object is created
and a stream is associated with the object

© Copyright aurionPro Solutions Ltd.


Streams(Contd.)
Thus, an object from which we can read a
sequence of bytes is input stream
Thus, an object to which we can write a
sequence of bytes is output stream
The source or destination of data can be files,
network connections or even blocks of
memory
The Java I/O class libraries allows user to
handle any data in the same way

© Copyright aurionPro Solutions Ltd.


Java.io package
Provides an extensive set of classes for
handling I/O to & from various devices
Contains many classes each with a variety
of member variables & methods
It is layered ie. It does not attempt to put
too much capability into 1 class
Instead a programmer can get the features
he wants by layering one class over another

© Copyright aurionPro Solutions Ltd.


I/O Handling
All Java programs automatically import
java.lang package
This package defines a class called System,
which encapsulates several aspects of run-
time environment
It contains three predefined stream variables
called in,out, and err (public static)

© Copyright aurionPro Solutions Ltd.


Input streams

© Copyright aurionPro Solutions Ltd.


Output streams

© Copyright aurionPro Solutions Ltd.


InputStream class
An abstract class that defines methods for
performing I/p
Serves as base class for all other
InputStream classes
Defines a basic interface for reading
streamed bytes of information
Data in InputStream is transmitted one byte
at a time

© Copyright aurionPro Solutions Ltd.


InputStream class :
some methods
int read() : Returns an integer
representation of the next available byte of
input
int read(byte buffer[]):
int read(byte buffer[], int offset, int
numbytes)
int available()
void close()
void mark(int numbytes)

© Copyright aurionPro Solutions Ltd.


Using the Stream
variables
import java.io.*;
class ReadKeys {
public static void main (String args[]) {
StringBuffer sb = new StringBuffer();
char c;
try {
while((ch =(char)System.in.read()) !=
'\n')) { sb.append(c);
}
} catch (Exception e) { ... }
String s = new String(sb);
© Copyright aurionPro Solutions Ltd.
OutputStream
void write (int b): Writes a single byte to an
output stream
void write(byte buffer[])
void write(byte buffer[], int offset, int
noBytes)
void flush()
void close()

© Copyright aurionPro Solutions Ltd.


FileInputStrea
m
The FileInputStream class creates an
InputStream that you can use to read the
contents of a file. It has two constructors:
FileInputStream(String filepath) throws
FileNotFoundException
FileInputStream(File fileobj) throws
FileNotFoundException

© Copyright aurionPro Solutions Ltd.


FileOutputStre
am
The FileOutputStream class creates an
OutputStream that you can use to read the
contents of a file. It has two constructors:

FileOutputStream(String filepath)
FileOutputStream(File fileobj)

© Copyright aurionPro Solutions Ltd.


ByteArrayInputStream
ByteArrayInputStream is an implementation
of an input stream that uses a byte array as
the source. This class has two constructors ,
each of which requires a byte array to provide
the data source

ByteArrayInputStream(byte array[])

ByteArrayInputStream(byte array[],int start,int

numbytes)

© Copyright aurionPro Solutions Ltd.


Chaining of
streams
Each class accesses the output of the previous
class through the in variable
Example
FileOutputStream fos = new
FileOutputStream(c:\a.txt”);
DataOutputStream dos = new
DataOutputStream(fos);

© Copyright aurionPro Solutions Ltd.


Readers/Write
rs
Reader and Writer classes are designed for
character streams
Reader is an input character stream that
reads a sequence of Unicode characters
Writer is an output character stream that
writes a sequence of Unicode characters

© Copyright aurionPro Solutions Ltd.


Reader hierarchy

© Copyright aurionPro Solutions Ltd.


Writer hierarchy

© Copyright aurionPro Solutions Ltd.


File class
File class doesn’t operate on streams
Represents the pathname of a file or
directory in the host file system
Used to obtain or manipulate the information
associated with a disk file, such as
permissions, time, date, directory path etc
An object of File class provides a handle to a
file or directory and can be used to create,
rename or delete the entry

© Copyright aurionPro Solutions Ltd.


File class
Some methods
canRead()
exists()
isFile()
isDirectory()
getAbsolutePath()
getName()

© Copyright aurionPro Solutions Ltd.


methods
(Contd.)
getPath()
getParent()
Length() : returns length of file in bytes as long
lastModified()
Mkdir()
List() : obtain listings of directory contents

© Copyright aurionPro Solutions Ltd.


Serialization
Serializability of a class is enabled by the
class implementing the java.io.Serializable
interface. Classes that do not implement this
interface will not have any of their state
serialized or deserialized. All subtypes of a
serializable class are themselves serializable.
The serialization interface has no methods or
fields and serves only to identify the
semantics of being serializable

© Copyright aurionPro Solutions Ltd.


Object Serialization
Allows an object to be transformed into a
sequence of bytes that can be later re-created
into an original object
After deserialization, the object has the same
state as it had when it was serialized(barring
any data members that are not serialized)
For a object to be serialized, the class must
implement the Serializable interface

© Copyright aurionPro Solutions Ltd.


RandomAccessFile
RandomAccessFile encapsulates a random-
access file
RandomAccessFile(String FileObj, String
access);
RandomAccessFile(String filename, String
access)

access can be r or rw
void seek( long newPos);

© Copyright aurionPro Solutions Ltd.


Multithreading in Java

© Copyrights aurionPro Solutions Ltd.


Multithreading
A multithreaded program contains two or
more parts that can run concurrently. Each
part of that program is called thread, and
each thread defines a separate path of
execution
There are two distinct types of multitasking:
process based & thread based
Thread is also known as lightweight process

© Copyright aurionPro Solutions Ltd.


Multithreading
The Main thread
When a Java program starts up, there is
already one thread running
 It is the thread from which other “child”
threads will be spawned
 It must be the last thread to finish execution.
When the main thread stops, your program
terminates
If the main thread finishes before a child thread
has completed, then the Java run-time system
may hang

© Copyright aurionPro Solutions Ltd.


Main Thread
 Although the main thread is called automatically when
program starts, it can be controlled by a thread object

 How? Obtain a reference to it by calling the method


currentThread() (a public static member of Thread class)
 static Thread currentThread(){ }

 This returns a reference to the thread in which it is called.


Once a reference to the main thread is obtained, it can be
controlled just like any other thread

© Copyright aurionPro Solutions Ltd.


Multithreading
Creating new Threads
java.lang.Thread
Creating a thread involves two steps: writing
the code that is executed in the thread and
writing the code that starts the thread
There are two ways to create a thread
Implementing Runnable interface
Extending Thread class

© Copyright aurionPro Solutions Ltd.


Runnable
interface
Need to implement run()
public abstract void run()
Instantiate an object of type Thread within
that class Thread defines several
constructors
Thread ( Runnable threadOb, String
threadName );
The new thread will not start running until its
start() method isn’t invoked
In turn, start() executes a call to run().
synchronized void start ( )
© Copyright aurionPro Solutions Ltd.
Extending
Thread class
The extending class must override the run()
method, which is the entry point for the new
thread
It must also call start() to begin execution of
the new thread

© Copyright aurionPro Solutions Ltd.


LifeCycle of Thread
Start Ready to run Leaving non-runnable
scheduling

Entering Non-runnable state


Running Waiting Sleeping Blocked
non-runnable

Terminates

Dead

© Copyright aurionPro Solutions Ltd.


States of Java Thread
 Not Runnable
 Still alive, but it is not eligible for execution
 It can move to not runnable stage because of
following reasons:

4. The thread is waiting for an I/O operation to


complete
5. The thread has been put to sleep for a certain
period of time (using the sleep() method)
6. The wait() method has been called
7. The thread has been suspended (using
suspend() method)
© Copyright aurionPro Solutions Ltd.
States of Java
Thread
 Dead
When a thread terminates, it is DEAD. Threads can
be DEAD in a variety of ways which include

1. When its run() method returns


2. When stop() or destroy() method is called

© Copyright aurionPro Solutions Ltd.


Methods invoked on
Threads
interrupt() : interrupts a thread

interrupted() : true if current thread has been


interrupted and false otherwise

isInterrupted() : determines if a particular


thread is interrupted

stop() : stops a thread by throwing a


ThreadDeath object which is a subclass of
error
© Copyright aurionPro Solutions Ltd.
The Thread Class
Methods
getPriority(): Obtains thread priority

start(): To start the operation of a thread

sleep(): suspends the thread for some time

run(): body of the thread

suspend()/resume(): suspends a thread &


resumes
© Copyright aurionPro Solutions Ltd.
Methods invoked on
Threads
getName(): returns the name of the thread
toString(): returns a string consisting of the
name of the thread, priority of the thread and
the thread’s group
currentThread(): returns a reference to the
current Thread
join(): waits for the thread to which the
message is sent to die before the current
thread can proceed

© Copyright aurionPro Solutions Ltd.


invoked on
Threads
isAlive(): returns true if start has been called
but stop has not
setName(): sets the name of the thread
Yield(): Causes the currently executing
thread object to temporarily pause and allow
other threads to execute

© Copyright aurionPro Solutions Ltd.


VS Nonpre-
emptive
Pre-emptive : The OS interrupts programs
without consulting them
Non pre-emptive: The programs are
interrupted only when they are ready to
yield control

© Copyright aurionPro Solutions Ltd.


Scheduling & Priority
Thread-scheduling: A mechanism used to
determine how runnable threads are
allocated CPU time
A Thread-scheduling mechanism is either
preemptive or non preemptive
Scheduling can be controlled through
priorities
 setPriority() getPriority()
Three types of priorities can be set viz
MIN_PRIORITY, NORM_PRIORITY, MAX_PRIORITY

© Copyright aurionPro Solutions Ltd.


Scheduling &
Priority
The job of Java scheduler is to keep a highest
priority thread running at all times
If timeslicing is available, it ensures that
several equally high - priority threads execute
for a quantum in a round - robin fashion

© Copyright aurionPro Solutions Ltd.


implementation
dependent
The early Solaris Java platform runs a thread
of a given priority to completion or until a
higher priority thread becomes ready
At that point preemption occurs, I.e the
processor is given to the higher - priority
thread while the previously running thread
must wait

© Copyright aurionPro Solutions Ltd.


Multithreading policies
In 32-bit Java implementations for Win ‘95 &
Win NT, threads are time sliced
Each thread is given a limited amount of
time to execute on a processor
When that time expires the thread is made
to wait while other threads of equal priority
get their chance to use their quantum in
round - robin fashion

© Copyright aurionPro Solutions Ltd.


Multithreading
policies
Thus, on Win ‘95 and Win NT, a running
thread can be pre - empted by a thread of
equal priority
Whereas on the early solaris implementation,
a running thread can only be pre-empted by a
higher priority thread

© Copyright aurionPro Solutions Ltd.


Thread Synchronization
Implemented using synchronized keywords
A method can be synchronized so that only
one thread at a time can access the method
This is possible using a technique called as
object monitor
Even an object can be synchronized

© Copyright aurionPro Solutions Ltd.


Inter thread
Communication
 final void wait(): tells the calling thread to
give up the monitor and go to sleep until
some other thread enters the same monitor
and calls notify()

final void notify(): wakes up the first thread


that called wait() on the same object

final void notifyall(): wakes up all the threads


that called wait() on the same object. The
highest priority thread will run first
© Copyright aurionPro Solutions Ltd.
Networking

© Copyrights aurionPro Solutions Ltd.


Networking
Basics
Computers running on the Internet
communicate to each other using either the
Transmission Control Protocol (TCP) or the
User Datagram Protocol (UDP).
 When you write Java programs that
communicate over the network, you are
programming at the application layer.
You can use the classes in the java.net
package.

© Copyright aurionPro Solutions Ltd.


TCP
When two applications want to communicate
to each other reliably, they establish a
connection and send data back and forth over
that connection.
 TCP guarantees that data sent from one end
of the connection actually gets to the other
end and in the same order it was sent.
Otherwise, an error is reported.
The Hypertext Transfer Protocol (HTTP), File
Transfer Protocol (FTP), and Telnet are all
examples of applications that require a
reliable communication channel.

© Copyright aurionPro Solutions Ltd.


UDP
UDP (User Datagram Protocol) is a protocol
that sends independent packets of data,
called datagrams, from one computer to
another with no guarantees about arrival.
UDP is not connection-based like TCP.
e.g. An application which sends current time.

© Copyright aurionPro Solutions Ltd.


Understanding
Ports
A computer has a single physical connection to the
network. All data destined for a particular computer
arrives through that connection. However, the data
may be intended for different applications running on
the computer. So how does the computer know to
which application to forward the data? Through the
use of ports.
The computer is identified by its 32-bit IP address,
which IP uses to deliver data to the right computer on
the network. Ports are identified by a 16-bit number,
which TCP and UDP use to deliver the data to the right
application.
Port numbers range from 0 to 65,535 because ports
are represented by 16-bit numbers. The port numbers
ranging from 0 - 1023 are restricted; they are
reserved for use by well-known services such as HTTP
and FTP and other system services.

© Copyright aurionPro Solutions Ltd.


java.net
The URL, URLConnection, Socket, and
ServerSocket classes all use TCP to
communicate over the network. The
DatagramPacket, DatagramSocket, and
MulticastSocket classes are for use with UDP.

© Copyright aurionPro Solutions Ltd.


Socket
A socket is one endpoint of a two-way
communication link between two programs
running on the network. A socket is bound to
a port number so that the TCP layer can
identify the application that data is destined
to be sent.

© Copyright aurionPro Solutions Ltd.


Abstract
Window Toolkit

© Copyrights aurionPro Solutions Ltd.


Introduction to AWT
AWT: Abstract Windows Toolkit package
Number of classes and interfaces to create
and manage windows
A standard way to provide graphical user
interface(GUI) in Java
AWT supports even the GUI based
applications

© Copyright aurionPro Solutions Ltd.


Window Fundamentals
The awt defines the various kinds of windows
according to class hierarchy that adds
functionality and specificity at each level
At the highest level of hierarchy is
Component class
An abstract class encapsulating all attributes of
a visual component
All methods regarding the painting displaying
the component, positioning, resizing, event
handling are defined in this class

© Copyright aurionPro Solutions Ltd.


Windows class
hierarchy
Java.lang.object

GUI control components are


Components concrete subclasses of this class.
(abstract)

Container
(abstract)

Panel Window

Java.applet.Applet Dialog Frame

© Copyright aurionPro Solutions Ltd.


GUI Control
Components
Button
Canvas
Checkbox
Choice
Label
List
Scrollbar
TextField
TextArea

© Copyright aurionPro Solutions Ltd.


Menu Components
Java.lang.object

Menu Component
(abstract)

Menubar MenuItem

Menu CheckboxMenuItem

PopupMenu

© Copyright aurionPro Solutions Ltd.


© Copyrights aurionPro Solutions Ltd.
Layouts
FlowLayout
GridLayout
BorderLayout
CardLayout
BoxLayout

© Copyright aurionPro Solutions Ltd.


BoxLayout
BoxLayout either stacks its components on
top of each other (with the first component at
the top) or places them in a tight row from
left to right
Demo : ListDialog.java
Using Fillers : Glue, RigidArea

© Copyright aurionPro Solutions Ltd.


GridBagLayou
t
A GridBagLayout places components in a grid
of rows and columns, allowing specified
components to span multiple rows or columns
Constraints
Gridx,gridy: Specify the row and column at the
upper left of the component
gridwidth, gridheight: Specify the number of
columns (for gridwidth) or rows (for gridheight)
in the component's display area

© Copyright aurionPro Solutions Ltd.


GridBagLayout
Fill: Used when the component's display area is
larger than the component's requested size to
determine whether and how to resize the
component

© Copyright aurionPro Solutions Ltd.


GridBagLayou
t
Constraints
ipadx, ipady : Specifies the internal padding:
how much to add to the minimum size of the
component
insets : specifies the external padding of the
component -- the minimum amount of space
between the component and the edges of its
display area
anchor : used when the component is smaller
than its display area to determine where
(within the area) to place the component
weightx, weighty : Weights are used to
determine how to distribute space among
© Copyright aurionPro Solutions Ltd.
Rendering graphics
Graphics
Font
FontMetrics
Color
GraphicsEnvironment
GraphicsEnvironment gEnv =
GraphicsEnvironment.getLocalGraphicsEnviro
nment();
String envfonts[] =
gEnv.getAvailableFontFamilyNames();

© Copyright aurionPro Solutions Ltd.


Rendering
graphics
Toolkit
Image
Double-buffering

© Copyright aurionPro Solutions Ltd.


© Copyrights aurionPro Solutions Ltd.
Handling
Mechanisms
Ignore the event
Have the event handled by the component
from where the event originated
Delegate the event handling to some other
object or objects, called listeners

© Copyright aurionPro Solutions Ltd.


Event Delegation
Event classes that can encapsulate
information about different types of user
interaction
Event source objects that inform event
listeners about events when these occur and
supply the necessary information about these
events
Event listener objects that are informed by an
event source when designated events occur,
so that they can take appropriate action

© Copyright aurionPro Solutions Ltd.


Inheritance diagram of the event
classes
Event
Object

AWT Event

Action Adjustment Component Item Text


Event Event Event Event Event

Container Focus Input Paint Window


Event Event Event Event Event

Key Mouse
Event Event
© Copyright aurionPro Solutions Ltd.
Event sources,classes &
interfaces
Event Type Event Source Listener registration Event listener
and removal methods interface
provided by the implemented by
source a listener
ActionEvent Button addActionListener ActionListener
List removeActionListener
MenuItem
TextField
Adjustment Scrollbar addAdjustmentListener AdjustmentListene
Event removeAdjustmentListe r
ner
ItemEvent Choice addItemListener ItemListener
Checkbox removeItemListener
CheckboxMenuItm
List
TextEvent TextArea addTextListener TextListener
TextField removeTextListener

Key Event Component addKeyListener KeyListener


removeKeyListener

© Copyright aurionPro Solutions Ltd.


Event sources,classes &
interfaces
MouseEvent Component addMouseListener MouseListener
removeMouseListener MouseMotionListener
addMouseMotionLister
removeMouseMotionListener

WindowEvent Window addWindowListener WindowListener


removeWindowListener
FocusEvent Component addFocusListener FocusListener
removeFocusListener
ComponentEv Component addComponentListener ComponentListener
ent removeComponentListener
ContainerEve Component AddContainerListener ContainerListener
nt removeContainerListener

© Copyright aurionPro Solutions Ltd.


Event listeners and
methods
Event Listener Event Listener Methods
Interface
ActionListener actionPerformed( ActionEvent evt)
AdjustmentListener adjustmentValueChanged(AdjustmentEvent
evt)
ItemListener itemStateChanged(ItemEvent evt)
TextListener textValueChanged(TextEvent evt)
WindowListener windowActivated(WindowEvent evt)
windowClosed(WindowEvent evt)
windowIconified(WindowEvent evt)
windowDeiconified(WindowEvent evt)
windowDeactivated(WindowEvent evt)
windowOpened(WindowEvent evt)
windowClosing(WindowEvent evt)

MouseMotionListener mouseMoved(MouseEvent evt)


mouseDragged(MouseEvent evt)

© Copyright aurionPro Solutions Ltd.


Event listeners and
methods
MouseListener mouseClicked(MouseEvent evt)
mousePressed(MouseEvent evt)
mouseReleased(MouseEvent evt)
mouseEntered(MouseEvent evt)
mouseExited(MouseEvent evt)
KeyListener keyPressed(Keyevent evt)
keyReleased(Keyevent evt)
keyTyped(Keyevent evt)

FocusListener focusGained(focusEvent evt)


focusLost(focusEvent evt)

ContainerListener componentAdded( ComponentEvent evt)


componentRemoved( ComponentEvent evt)
ComponentListen componentHidden( ComponentEvent evt)
er componentMoved( ComponentEvent evt)
componentResized( ComponentEvent evt)
componentShown( ComponentEvent evt)

© Copyright aurionPro Solutions Ltd.


Low level event listener Low level event listener
interface adapter
ComponentListener ComponentAdapter
ContainerListener ContainerAdapter
FocusListener FocusAdapter
KeyListener KeyAdapter
MouseListener MouseAdapter
MouseMotionListener MouseMotionAdapter
WindowListener WindowAdapter

• Event Listeners as anonymous inner classes

© Copyright aurionPro Solutions Ltd.


Demo : Event Handling
Beeper.java, MouseEventListener.java, MultiListener.java

© Copyright aurionPro Solutions Ltd.


© Copyrights aurionPro Solutions Ltd.
What is Swing?
Swing is advertised as a set of customizable
graphical components whose look-and-feel
can be dictated at runtime
Swing is built on top of the core 1.1 and 1.2
AWT libraries
In JDK 1.1, the Swing classes must be down­
loaded separately and included as an
archive file on the classpath (swingall.jar).
JDK 1.2 comes with a Swing distribution

© Copyright aurionPro Solutions Ltd.


Swing
features:
Pluggable Look & Feel
Swing is capable of emulating several look-and-
feels, and currently includes support for
Windows 98 and Unix Motif

Lightweight Components
Components are not dependent on native peers
to render themselves. Instead, they use
simplified graphics primitives to paint
themselves on the screen and can even allow
portions to be transparent

© Copyright aurionPro Solutions Ltd.


Swing
Components
There are various swing components
available
Some of them are mentioned below:
JButton, JLabel, JTextfield, JComboBoxes etc.
JTable, JList, JTree, JSliderPane, JOptionPane etc.
Containers – JFrame, JApplet, JPanel etc.

© Copyright aurionPro Solutions Ltd.


Swing
Hierarchy
Java.lang.object

GUI control components are


JComponent concrete subclasses of this class.
(abstract)

JContainer
(abstract)

JPanel JWindow

Java.applet.Applet Dialog Frame

© Copyright aurionPro Solutions Ltd.


JComponent
Class
Tool tips: setToolTipText method
Painting and borders: The setBorder method
allows you to specify the border that a
component displays around its edges
Application-wide pluggable look and feel
Double buffering: Double buffering smooths
on-screen painting
Key bindings

© Copyright aurionPro Solutions Ltd.


JComponent
API
Customizing Component Appearance: Border,
Foreground, Background, Font etc.
Setting and Getting Component State
Handling Events: add Listener methods
Painting Components: repaint, revalidate
Dealing with the Containment Hierarchy: add,
remove
Laying Out Components: getPreferedSize

© Copyright aurionPro Solutions Ltd.


Top Level
Container
Swing provides three generally useful top-level
container classes: JFrame, JDialog, and JApplet
Points to remember
every GUI component must be part of a
containment hierarchy
Each GUI component can be contained only once
Each top-level container has a content pane

© Copyright aurionPro Solutions Ltd.


Demo : First Swing
Program
SwingApplication.java

© Copyright aurionPro Solutions Ltd.


Demo : Top Level
Container
FrameDemo.java

© Copyright aurionPro Solutions Ltd.


Frames API
Creating and Setting Up a Frame :
defaultOperations, IconImage etc.
Setting the Window Size and Location : pack,
setSize, setBounds etc.

© Copyright aurionPro Solutions Ltd.


Demo : Frame Demo
FrameDemo2.java

© Copyright aurionPro Solutions Ltd.


What is an
applet ?
Applets are small programs stored over web
server
Transported over the net
Installed automatically
Run as a part of web page
Need an environment of web browser

© Copyright aurionPro Solutions Ltd.


Applet basics
Any applet has to inherit from an Applet class
The methods in the Applet class are
init()
start()
paint(Graphics g)
stop()
destroy()

© Copyright aurionPro Solutions Ltd.


Applet basics(Contd.)
Adding an applet to html document
<html>
<applet code=“myapplet.class” width=400
height=400>
</applet>
</html>
Running an Applet
c:\appletviewer ex.html

© Copyright aurionPro Solutions Ltd.


Applet
basics(Contd.)
Applets do not have a main method
Applets must run under the environment of
web browser
Applets do not have the right/permission to
access the file system on client machine
They can not perform any I/O operation

© Copyright aurionPro Solutions Ltd.


A Simple Applet
import java.applet.Applet;
import java.awt.*;
public class simpleapp extends
Applet {
public void init(){ //any initialization
setBackground(Color.black);
setForeground(Color.yellow);
} public void paint(Graphics g){
g.drawString(“Hello
World”,100,100);
}
© Copyright aurionPro Solutions Ltd.
Other Applet
methods
repaint(): to request painting again
update()
showStatus(String)
getDocumentBase(): URL of HTML file
getCodeBase(): URL of applet file
getParameter(String): to retrieve the
parameter value from HTML document

© Copyright aurionPro Solutions Ltd.


JAR files
< applet archive=”appletbundle.jar”
code=”appletname.class” width=w
height=h></applet>
JAR files can be made by using the jar tool
Jar cf appletbundle.jar *. class image.* ………
To display the content of the jar file
Jar tf appletbundle.jar
To extract the content of the jar file
Jar xvf appletbundle.jar

© Copyright aurionPro Solutions Ltd.


Applets
Applet Life Cycle
Features
You add components to a Swing applet's
content pane, not directly to the applet
The default layout manager for a Swing
applet's content pane is BorderLayout
You should not put painting code directly in a
JApplet object

© Copyright aurionPro Solutions Ltd.


Applets
(Contd.)
Threads in Applet
It's generally considered safe to create and
manipulate Swing components directly in the
init method

© Copyright aurionPro Solutions Ltd.


Applets
(Contd.)
Embedding an Applet in an HTML Page
<applet code="TumbleItem.class"
codebase="example-1dot4/"
archive="tumbleClasses.jar
tumbleImages.jar" width="600"
height="95">
<param name="maxwidth" value="120">
<param name="nimgs" value="17">
<param name="offset" value="-57">
<param name="img" value="images/tumble">

© Copyright aurionPro Solutions Ltd.


Applets
(Contd.)
Your browser is completely ignoring the
<applet> tag! </applet>

© Copyright aurionPro Solutions Ltd.


Demo : Applet Demo
HelloSwingApplet.java

© Copyright aurionPro Solutions Ltd.


Painting
JFrame- Content Pane – JPanel – JButton,
JLabel
The top-level container, JFrame, paints itself
The content pane first paints its background
and it paints its border, it then tells the JPanel
to paint itself, finally the panel asks its children
to paint themselves

© Copyright aurionPro Solutions Ltd.


© Copyrights aurionPro Solutions Ltd.
Design Goals
To build a set of extensible GUI components
to enable developers to more rapidly develop
powerful Java front ends for commercial
applications
Be implemented entirely in Java to promote
cross-platform consistency and easier
maintenance

© Copyright aurionPro Solutions Ltd.


Design Goals
Provide a single API capable of supporting
multiple look-and-feels so that developers and
end-users would not be locked into a single
look-and-feel
Enable the power of model-driven
programming without requiring it in the
highest-level API
Adhere to JavaBeans design principles to
ensure that components behave well in IDEs
and builder tools

© Copyright aurionPro Solutions Ltd.


Roots in MVC
MVC architecture calls for a visual application
to be broken up into three separate parts:
A model that represents the data for the
application
The view that is the visual representation of
that data
A controller that takes user input on the view
and translates that to changes in the model

© Copyright aurionPro Solutions Ltd.


The delegate
Different view and controller became a
difficult proposition
So the three entities collapsed into two with a
single UI (user-interface) object
Component and UI delegate object

© Copyright aurionPro Solutions Ltd.


What MVC
facilitates?
Separating the model definition from a
component facilitates model-driven
programming in Swing

The ability to delegate some of a component's


view/controller responsibilities to separate
look-and-feel objects provides the basis for
Swing's pluggable look-and-feel architecture

© Copyright aurionPro Solutions Ltd.


model
architecture

Model Component
Interface
ButtonModel Jbutton, JCheckBox, JRadioButton,
JMenuItem
BoundedRangeMod JProgressBar, JScrollBar, JSlider
el
Document JTextField, JTextArea, JTextPane
etc.

© Copyright aurionPro Solutions Ltd.


Types of
Models
GUI-state models define the visual status of a
GUI control
relevant only in the context of a graphical user
interface (GUI)
Useful if multiple GUI controls are linked to a
common state e.g. shared white board
programs
E.g ButtonModel, BoundedRangeModel

© Copyright aurionPro Solutions Ltd.


Types of Models(Contd.)
Application-data models
represents some quantifiable data that has
meaning primarily in the context of the
application
Like the value of a cell in a table
E.g. TableModel, Document, ListModel,
ComboBoxMdel

© Copyright aurionPro Solutions Ltd.


The separable
model API
Implemented as a JavaBeans bound property
for the component
If you don't set your own model, a default is
created and installed internally in the
component
For more complex models like Jlist or Jtable
abstract model implementations are provided

© Copyright aurionPro Solutions Ltd.


Model change
notification
Models must be able to notify any interested
parties (such as views) when their data or
value changes
Swing models use the JavaBeans Event model
Two Approaches for notification
Lightweight Notification
 a single event instance can be used for all
notifications from a particular model

© Copyright aurionPro Solutions Ltd.


Model change
notification
Stateful Notification
 describes more precisely how the model has
changed

© Copyright aurionPro Solutions Ltd.


© Copyrights aurionPro Solutions Ltd.
Demos
Button, CheckBox, RadioButton
Labels
ComboBoxes
Menus
ProgressBars, Sliders, Spinners

© Copyright aurionPro Solutions Ltd.


© Copyrights aurionPro Solutions Ltd.
Scroll Pane
Pane
Split
Places 2 or more components side by side in
a single frame
Pane can horizontal or vertical

Scroll
Provide automatic scrolling facility
Horizontal and vertical headers are possible

© Copyright aurionPro Solutions Ltd.


List
Component
List component consists of three parts
List data is assigned to a model i.e. ListModel
User Selection : User Selection Model
Visual Appearance : Cell Renderer
Demo : SimpleList.java
List model is a simple interface used to access
data in the list
Demo : ListModelExample.java

© Copyright aurionPro Solutions Ltd.


List
Component
Cell Rendering
ListExample.java. BookCellRenderer.java

© Copyright aurionPro Solutions Ltd.


Table
Component
JTable class : demo SimpleTable.java
The classes and interfaces involved are
TableColumn, TableColumnModel
TableModel
TableCellEditor
TableCellRenderer

© Copyright aurionPro Solutions Ltd.


Table
Columns
The basic unit in swing table is a column and
not a cell
Classes involved : TableColumn ,
TableColumnModel
TableColumn : It’s a starting point for
building columns in the table
Properties : cellEditor,
cellRenderer,HeaderRenderer
TableColumnModel manages the column
selections and column spacing
 Demo of TableColumnModel :
ColumnExample.java,SortinColumnModel.java
© Copyright aurionPro Solutions Ltd.
Table Data
The actual data that’s displayed in JTable is
stored in a TableModel
TableModel interface : has access to all cell
values in a table
columnCount, rowCount
Cell methods
 Object getValueAt(int, int)
 boolean isCellEditable(int,int)

 void setValueAt(Object,int,int)

© Copyright aurionPro Solutions Ltd.


Table Data
SubClasses : AbstractTableModel,
DefaultTableModel

© Copyright aurionPro Solutions Ltd.


Editing and
Rendering
Possible to build customized editors and
renderers for the cell
Default are:
Boolean - JCheckBox
Number - right aligned JTextField
Object - JTextField
ImageIcon

© Copyright aurionPro Solutions Ltd.


Rendering
(contd..)
TableCellRenderer
Componet getTableCellRendererComponent(..)
Demo : FileTable2.java, FileModel.java,
BigRenderer.java
TableCellEditor
Componet getTableCellEditorComponent(..)
Selecting Table Entries
Uses ListSelectionModel
Row and Column selection models are different
objects

© Copyright aurionPro Solutions Ltd.


Tree
Component
Tree components are meant to view
hierarchical information
It makes traversal and manipulation of that
information much more manageable
A tree consists of nodes. Nodes are of two
types
A node which consists of objects and a
reference to other nodes
A node which only consists of objects
Swing implements tree structure using JTree
class and its models
© Copyright aurionPro Solutions Ltd.
Tree
Terminology
Node : An entry in the tree
Root : Top level node
Child : All nodes except root
Parent : Nodes attached above the
node
Sibling : Any child of the parent and self
Descedent : Any child including the node
Ancestor : Any parent including the
node
Level : Distance from the node to the
root

© Copyright aurionPro Solutions Ltd.


Tree
Terminology
Path : A list of nodes leading from one
node to another
Collapsed : Invisible children
Expanded : Visible children

© Copyright aurionPro Solutions Ltd.


Tree Models
Two interfaces are particularly important
TreeModel : describes how to work with tree
data
TreeSelectionModel : describes how to select
the modes
DefaultTreeModel class puts together a basic
tree model using TreeNode objects
Each node’s data is really just an Object
reference, pointing to just about any object

© Copyright aurionPro Solutions Ltd.


Tree Models
(contd.)
MutableTreeNode defines the requirements
for a tree node object that can change -- by
adding or removing child nodes, or by
changing the contents of a user object stored
in the node
DefaultMutableTreeNode
Mutation Methods: insert, remove etc
Structure Methods : provides methods to
modify and querying the structure
Enumeration Methods

© Copyright aurionPro Solutions Ltd.


Tree Selections
Selections are based on rows and paths
Path contains the list of nodes from the root
of the tree to another node
Rows are completely dependent on the visual
display of the tree
Depending on the application the row or path
selection can be used

© Copyright aurionPro Solutions Ltd.


Demo : Tree Demo
TreeDemo.java

© Copyright aurionPro Solutions Ltd.


© Copyrights aurionPro Solutions Ltd.
Root Panes
Each top-level container relies on a reclusive
intermediate container called the root pane
Four parts:
Glass Pane: hidden by default
Layered Pane
Content Pane
Optional Menu Bar

© Copyright aurionPro Solutions Ltd.


Java Database
Connectivity

© Copyrights aurionPro Solutions Ltd.


Java Database
Connectivity
JavaSoft worked with D/B tool vendors to
provide DBMS independent mechanism to
write client side applications
The result is JDBC API
 JDBC API is designed to allow developers to
create database front ends without having to
continually rewrite the code
An API that is D/B independent and uniform
across databases

© Copyright aurionPro Solutions Ltd.


Java Database
Connectivity
A standard to write which takes all app.
designs into account
This is possible through a set of interface that
are implemented by the driver
Driver is responsible for converting a
standard JDBC call to a native call

© Copyright aurionPro Solutions Ltd.


What is JDBC
Java Database Connectivity (JDBC) is a
standard SQL database access interface,
providing uniform access to a wide range of
relational databases

JDBC provides a common base on which


higher level tools and interfaces can be built

© Copyright aurionPro Solutions Ltd.


What does JDBC Do ?
JDBC makes it possible to do three things:

1) Establish a connection with a database


2) Send SQL statements
3) Process the results

© Copyright aurionPro Solutions Ltd.


Why JDBC ?
Java is a write once, run anywhere language
Java based clients are thin client
Suited for network centric models
It provide a clean , simple, uniform vendor
independent interface
JDBC support all the advance features of
latest version ANSI SQL
JDBC API provides a rich set of methods

© Copyright aurionPro Solutions Ltd.


Database
Connectivity
JDBC
ODBC

© Copyright aurionPro Solutions Ltd.


ODBC Architecture
Application Application Application
ODBC API

ODBC Driver Manager

Oracle SQL Server DB 2 Service


Driver Driver Driver Provider
SQL * Net Net Lib ESQL/DRDA API

Oracle SQL
DB 2
Database Server

© Copyright aurionPro Solutions Ltd.


JDBC Architecture
Application Application JDBC API
Application

JDBC Driver Manager

Oracle SQL Server JDBC -ODBC


Driver Service
Driver Driver
Provider
SQL * Net Net Lib
API
ODBC Driver
Oracle
SQL Server
Database Sybase

© Copyright aurionPro Solutions Ltd.


just use ODBC
from Java?
ODBC relies on the multiple use of void *
pointers and other C features that are not
natural in java
ODBC driver manager and drivers must be
manually installed on every client machine.
JDBC code is automatically installable,
portable, and secure
ODBC is procedure oriented, while JDBC is
object oriented

© Copyright aurionPro Solutions Ltd.


Two-tier and Three-tier
Models
JDBC API supports both two-tier and three-tier models for database
access

JAVA Application Client Java Applet or


GUI HTML browser

JDBC
HTTP,RMI,CORBA

Application
Propriety server (JAVA) Business
protocol logic
Database JDBC
server
Propriety protocal
DBMS

Two-tier JDBC Three-tier JDBC


© Copyright aurionPro Solutions Ltd.
JDBC API - java.sql
Driver

Connection ResultSet

Interfaces
in java.sql
DatabaseMetaData
ResultSetMetaData

Statement PreparedStatement CallableStatement

© Copyright aurionPro Solutions Ltd.


JDBC components
Driver Manager

Driver

Connection

PreparedStatement Statement CalllableStatement

ResultSet ResultSet ResultSet

© Copyright aurionPro Solutions Ltd.


access from
Java
Steps Involved
Loading the Driver
Establishing the connection
Passing Sql Query

© Copyright aurionPro Solutions Ltd.


Loading Drivers
Class.forName()throws
ClassNotFoundException
- sun.jdbc.odbc.JdbcOdbcDriver
- jdbc.driver.oracle.OracleDriver
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"
);
}catch(ClassNotFoundException e) {
System.out.println(“Exception : “ + e);}

© Copyright aurionPro Solutions Ltd.


Types of
Driver
Type I : Jdbc-Odbc Bridge Driver
Type II : Partly Java, partly native code
implementing Vendor specific
API
Type III : Pure Java driver requesting either
to type I or II as another layer
Type IV : Pure Java requesting directly to the
database

© Copyright aurionPro Solutions Ltd.


Establishing Connection
A JDBC URL has the following syntax
String url= jdbc:<subprotocol>:<subname>
// for odbc
String url= “jdbc:odbc:employee” ;
// for jdbc
String url=
“jdbc:oracle:thin:@tech:1521:ORCL” ;
Connection con =
DriverManager.getConnection
(“url,"myLogin", "myPassword")

© Copyright aurionPro Solutions Ltd.


Retrieving Data from
Table
ResultSet executeQuery( String sql) throws
SQLException
ResultSet rs = stmt.executeQuery("SELECT
name, age FROM student");
 Retrieving data from Resultset
 boolean next( ) throws SQLException
 void Close ( ) throws SQLException

 XXX getXXX( int index ) throws SQLException

© Copyright aurionPro Solutions Ltd.


data from
ResultSet
 String query = " SELECT name, age FROM student
";
 ResultSet rs = stmt.executeQuery(query);

 while (rs.next()) {

 String s = rs.getString("name");
 BigDecimal n =
rs.getBigDecimal("age");
 System.out.println(s + " " + n);
 }

The output will look something like this:


 Smith 20
 Rahul 19
© Copyright aurionPro Solutions Ltd.
RowSets
A RowSet object contains a set of rows from a
result set or some other source of tabular
data, like a file or spreadsheet. Because a
RowSet object follows the JavaBeans model for
properties and event notification, it is a
JavaBeans component that can be combined
with other components in an application

© Copyright aurionPro Solutions Ltd.


Types of
RowSets
JdbcRowSet: A connected scrollable
,updatable RowSet
CachedRowset:A disconnected RowSet
WebRowSet:A connected RowSet that uses
the HTTP protocol internally to talk to a Java
Servlet that provides data access

© Copyright aurionPro Solutions Ltd.


Inserting Data into
Tables
executeUpdate( ) throws SQLException
Statement stmt = con.createStatement();
stmt.executeUpdate("INSERT INTO student " +
"VALUES (1, 'Smith', ' Bombay' , 20, 7646234 ) )";
stmt.executeUpdate("INSERT INTO st_ course " +
"VALUES (1, 1, 01-01-1999, 'Very Good' )");

© Copyright aurionPro Solutions Ltd.


Updating
Tables
executeUpdate()
Statement stmt = con.createStatement();
stmt.executeUpdate( "UPDATE course”+ “SET
fees = fees+2000.00" );

© Copyright aurionPro Solutions Ltd.


Using
PreparedStatement
PreparedStatement prep =
con.prepareStatement( "UPDATE"+
" course values set fees = ? WHERE c-id = ?
");
prep.setInt(1, 2);
prep.setBigDecimal(2, 8000.00);
prep.executeUpdate ( );
prep.setInt(1, 4);
prep.setBigDecimal(2,
9000.00);prep.executeUpdate ( );

© Copyright aurionPro Solutions Ltd.


Connection
Pooling
DataSource:The JDBC 2.0 extension API
introduced the concept of data sources, which
are standard, general-use objects for
specifying databases or other resources to use

© Copyright aurionPro Solutions Ltd.


What is a
DataSource?
A DataSource object is the representation of a
data source in the Java programming
language. In basic terms, a data source is a
facility for storing data. It can be as
sophisticated as a complex database for a
large corporation or as simple as a file with
rows and columns. A data source can reside
on a remote server, or it can be on a local
desktop machine

© Copyright aurionPro Solutions Ltd.


What is a
DataSource?
Applications access a data source using a
connection, and a DataSource object can be
thought of as a factory for connections to the
particular data source that the DataSource
instance represents

© Copyright aurionPro Solutions Ltd.


r and
DataSource
 While directly creating a connection by
calling DriverManager.getConnection(..) , you
are creating a connection by yourself and
when closing close() on it, the link to
database is lost. On the other hand we get a
connection from a datasource, when you call
the close() on it, it will not close the link to
database, but will return to a connection pool
where it can be reused by some other
classes

© Copyright aurionPro Solutions Ltd.


DataSource(C
ontd.)
 It is always better to use a connection pool
because creating connections are expensive.
DataSource has its usability in the distributed
computing environment,as it can be used
with JNDI lookups
 Another major advantage is that the
DataSource facility allows developers to
implement a DataSource class to take
advantage of features like connection
pooling and distributed transactions

© Copyright aurionPro Solutions Ltd.


Using Callable
Statement
String sql=“execute getEmployes ? ”;
CallableStatement call=con.prepareCall(sql);

call.registerOutParameter(1,Types.INTEGER);
call.execute();
int val=call.getInt(1);
System.out.println(“There are ” +val + “ employees”);

© Copyright aurionPro Solutions Ltd.


Using Transactions
con.setAutoCommit(boolean commit)

con.commit()
con.rollback()

try {
con.setAutoCommit(false);
// perform transactions
con.commit()
con.setAutoCommit(true);
} catch (SQLException e) {
© Copyright aurionPro Solutions Ltd.
Collections
Framework in Java

© Copyrights aurionPro Solutions Ltd.


What is Collections
Framework?
A Collection is a group of objects
Collections framework provide a a set of
standard utility classes to manage
collections
Collections Framework consists of three
parts:
Core Interfaces
Concrete Implementation
Algorithms such as searching and sorting

© Copyright aurionPro Solutions Ltd.


Collections
Hierarchy

© Copyright aurionPro Solutions Ltd.


Basic
Operations
int size();
boolean isEmpty();
boolean contains(Object element);
boolean add(Object element);
boolean remove(Object element);
Iterator iterator();

© Copyright aurionPro Solutions Ltd.


Bulk
Operations
 boolean containsAll(Collection c);
 boolean addAll(Collection c);
 boolean removeAll(Collection c);
 boolean retainAll(Collection c);
 void clear();

© Copyright aurionPro Solutions Ltd.


Array
Operations
 Object[] toArray();
 Object[] toArray(Object a[]);

© Copyright aurionPro Solutions Ltd.


Collection Interfaces
Interfaces Description
Collection Defines the operations that all classes that maintain
collections typically implement
Set Maintains a set of unique elements.

SortedSet Maintains the elements in sorted order.

List An ordered collection (i.e. sequence). Duplicates


and multiple null values allowed.
Map For classes implementing key-value pair kind pf
mappings. Can not contain duplicate keys.
SortedMap Map is in the sorted key order.

© Copyright aurionPro Solutions Ltd.


Implementati
ons
Interfaces
Data Set SortedSet List Map SortedMap
Structures
Hashtable Hash Hash
Set Map
Resizable Array
Array List
Balanced TreeSet TreeMap
Tree
Linked List Linked
List

© Copyright aurionPro Solutions Ltd.


The Classes
 Legacy classes
 Vector
 HashTable
 Stack

© Copyright aurionPro Solutions Ltd.


Thank you

© Copyright aurionPro Solutions Ltd.

You might also like